package com.example.mvp.delegate;

import android.app.Activity;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

/**
 * App公共托管类
 * Created by sun.li on 2018/6/5.
 *
 * @author sun.li
 */

public abstract class BaseAppDelegate implements XDelegate {

    protected View rootView;

    protected final SparseArray<View> mViews = new SparseArray<View>();

    @Override
    public void create(LayoutInflater inflater, ViewGroup container) {
        int rootLayoutId = initLayoutRes();
        try {
            rootView = inflater.inflate(rootLayoutId, container, false);
        }catch (Exception e){

        }

    }

    @Override
    public int getOptionsMenuId() {
        return 0;
    }

    @Override
    public View getRootView() {
        return rootView;
    }

    public void setRootView(View rootView) {
        this.rootView = rootView;
    }

    private <T extends View> T bindView(int id) {
        if (null == mViews || null == rootView) {
            return null;
        }
        T view = (T) mViews.get(id);
        if (view == null) {
            view = (T) rootView.findViewById(id);
            mViews.put(id, view);
        }
        return view;
    }

    public <T extends View> T getView(int id) {
        return (T) bindView(id);
    }

    public void setOnClickListener(View.OnClickListener listener, int... ids) {
        if (ids == null) {
            return;
        }
        for (int id : ids) {
            if(null==getView(id)){
                continue;
            }
            getView(id).setOnClickListener(listener);
        }
    }

    /**
     * 初始化界面布局文件
     */
    protected abstract int initLayoutRes();

    public void toast(CharSequence msg) {
        if (null == rootView) {
            return;
        }
        Toast.makeText(rootView.getContext(), msg, Toast.LENGTH_SHORT).show();
    }

    public <T extends Activity> T getActivity() {
        if (null == rootView) {
            return null;
        }
        return (T) rootView.getContext();
    }

    @Override
    public void onDestroy() {

    }
}
